#include "downloader.h"
#include <QtWebKit/QWebView>
#include <QtWebKit/QWebFrame>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QMessageBox>
#include <QFileDialog>


Downloader::Downloader(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags), downloadReply(NULL)
{
	ui.setupUi(this);

	QRect winRect = rect();
	winRect.moveCenter( QDesktopWidget().availableGeometry().center() );
	move( winRect.topLeft() );

	networkManager = new QNetworkAccessManager(this);

	QObject::connect( ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addJSObject()) );
	ui.webView->load( QUrl("qrc:/GUI/Resources/main.ru.html") );
}

Downloader::~Downloader()
{

}

void Downloader::addJSObject()
{
	ui.webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("downloader"), this);
}

void Downloader::beginDownload(QString downloadUrl)
{
	downloadLocalFilePath = QFileDialog::getSaveFileName(this, tr("Download file"), QString(), tr("All files (*.*)"));
	downloadLocalFilePath = QDir::toNativeSeparators(downloadLocalFilePath);

	abortDownload();
	QNetworkRequest *request = new QNetworkRequest( QUrl(downloadUrl) );
	downloadReply = networkManager->get(*request);
	delete request;

	connect( downloadReply, SIGNAL(finished()), this, SLOT(endDownloadFile()) );
	connect( downloadReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progressDownloadFile(qint64, qint64)) );

	emit downloadingStart();
}

void Downloader::endDownloadFile()
{
	bool success = false;

	if (downloadReply && !downloadLocalFilePath.isEmpty() && downloadReply->error() == QNetworkReply::NoError)
	{
		QByteArray response = downloadReply->readAll();
		QFile file(downloadLocalFilePath);
		if ( file.open(QIODevice::WriteOnly) )
		{
			file.write(response);
			file.close();
			success = true;
		}
	}

	if (success)
		emit downloadingEnd("downloaded successful");
	else
		emit downloadingEnd("downloading failed");
}

void Downloader::progressDownloadFile(qint64 bytesReceived, qint64 bytesTotal)
{
	int percentage = bytesReceived * qint64(100) / bytesTotal;
	emit downloadingProgress(percentage);
}

void Downloader::abortDownload()
{
	if (downloadReply)
	{
		disconnect( downloadReply, SIGNAL(finished()), this, SLOT(endDownloadFile()) );
		disconnect( downloadReply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(progressDownloadFile(qint64, qint64)) );

		downloadReply->deleteLater();
		downloadReply = NULL;
	}
}
